//
//  Hud.swift
//  OnemeetingDemo
//
//  Created by 张衡 on 2019/12/5.
//  Copyright © 2019 www.onemeeting.1meetingIos. All rights reserved.
//

import Foundation

class Hud: NSObject {
    
    static let shared = Hud()
    var isClose:Bool = false
    var intrinsicSize:CGSize = CGSize.init(width: 42, height: 42) {
        didSet {
            if self.isClose == false {
                self.indicatorView.snp.updateConstraints { (make) in
                    make.width.equalTo(intrinsicSize.width)
                    make.height.equalTo(intrinsicSize.height)
                }
            }
        }
    }
    
    lazy var indicatorView: KRActivityIndicatorView = {
        let view = KRActivityIndicatorView.init(frame: CGRect.init(x: 0, y: 0, width: intrinsicSize.width, height: intrinsicSize.height), type: KRActivityIndicatorType.lineScaleParty, color: color_gray(120), padding: 10)
        return view
    }()
    
    class func show(msg:String="",window:NSWindow?=NSApplication.shared.mainWindow) {
        let new = window ?? NSApplication.shared.mainWindow
        if let inView = new?.contentView {
            if Hud.shared.isClose == false {
                Hud.dismiss()
            }
                
            let indicatorView = Hud.shared.indicatorView
            inView.addSubview(indicatorView)
            indicatorView.snp.makeConstraints { (make) in
                make.center.equalToSuperview()
                make.width.equalTo(Hud.shared.intrinsicSize.width)
                make.height.equalTo(Hud.shared.intrinsicSize.height)
            }
            Hud.shared.indicatorView.startAnimating()
            Hud.shared.isClose = false
        }
    }
    
    class func dismiss(window:NSWindow?=NSApplication.shared.mainWindow) {
        Hud.shared.indicatorView.stopAnimating()
        Hud.shared.indicatorView.removeFromSuperview()
        Hud.shared.isClose = true
    }
}

extension NSViewController {
    func hud(msg:String="") {
        if let window = self.view.window {
            Hud.show(msg: msg, window: window)
        }
    }
    
    func dismiss() {
        if let window = self.view.window {
            Hud.dismiss(window: window)
        }
        
    }
}
